'use strict';
const { Service } = require('egg');
// const uuidv4 = require('uuid/v4');
const Result = require('../util/result');
// const moment = require('moment');

class OrderMasterService extends Service {

  async index(query) {
    const info = await this.ctx.model.OrderMaster.findAndCountAll(query);
    return Result.success(info);
  }
  async create(data) {
    // const start = moment().format('YYYYMMDDhhmmss');
    const date = new Date();
    const start = date.getTime();
    const end = data.uid.toString().substr(0, 4);
    data.order_id = start.toString().concat(end);
    const info = await this.ctx.model.OrderMaster.create({ ...data });
    if (!info) return Result.fail();
    return Result.success(info);
  }
  async show(id) {
    const info = await this.findById(id);
    if (!info) return Result.warn(-1, 'id不存在');
    return Result.success(info);
  }

  async update(id, data) {
    const order = this.findById(id);
    if (!order) return Result.warn(-1, 'id不存在');
    const info = await this.ctx.model.OrderMaster.update({ ...data }, {
      where: {
        id,
      },
    });
    if (info[0] === 0) return Result.fail();
    const res = this.findById(id);
    return Result.success(res);
  }

  async destroy(id) {
    const order = await this.findById(id);
    if (!order) return Result.warn(-1, 'id不存在');
    const info = await this.ctx.model.OrderMaster.destroy({
      where: {
        id,
      },
    });
    if (info[0] === 0) return Result.fail();
    return Result.noDataSuccess();
  }

  async findAllOrder(res) {
    const { limit, uid } = res;
    const info = await this.ctx.model.OrderMaster.findAndCountAll({
      where: { uid },
      limit,
    });
    return Result.success(info);
  }

  async findByStatus(res) {
    const { limit, pay_status } = res;
    const info = await this.ctx.model.OrderMaster.findAndCountAll({
      where: { pay_status },
      limit,
    });
    return Result.success(info);
  }

  async findById(id) {
    const info = await this.ctx.model.OrderMaster.findByPk(id);
    return info;
  }

  // async getByUid(res)
}

module.exports = OrderMasterService;
